package demo.oslutschyk;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.ResultSetMetaData;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JdbcAdapter extends JdbcManager {
    public static <T> List<T> get(String query, Class<T> type) {
        List list = new ArrayList();
        try {
            ResultSet rs = getStatement().executeQuery(query);
            ResultSetMetaData rsmd = rs.getMetaData();
            int numberCols = rsmd.getColumnCount();
            String[] colNames = new String[numberCols];
            for (int i = 1; i <= numberCols; i++) {
                colNames[i - 1] = rsmd.getColumnLabel(i);
            }
            while (rs.next()) {
                Map<String, Object> fieldsMap = new HashMap<String, Object>();
                for (String columnName : colNames) {
                    fieldsMap.put(("get"+columnName).toUpperCase(), rs.getObject(columnName));
                }
                list.add(type.cast(Proxy.newProxyInstance(JdbcAdapter.class.getClassLoader(), new Class<?>[]{type}, new ResultSetResolver(fieldsMap))));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return list;
    }
}

class ResultSetResolver implements InvocationHandler {
    private Map<String, Object> fieldsMap;

    ResultSetResolver(Map<String, Object> fieldsMap) {
        this.fieldsMap = fieldsMap;
    }


    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String interceptedMethod=method.getName();
        return fieldsMap.get(interceptedMethod.toUpperCase());
    }
}



